package com.java.second_goods.controller;

import com.java.second_goods.common.AjaxResult;
import com.java.second_goods.common.utils.FileUtils;
import com.java.second_goods.common.utils.Md5Utils;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 *
 * @author clothing-rental
 */
@RestController
@RequestMapping("api/file")
public class FileController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.allowed-types}")
    private String allowedTypes;

    @Value("${file.upload.max-size}")
    private long maxFileSize;

    /**
     * 文件上传接口
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }

        // 检查文件大小
        if (file.getSize() > maxFileSize) {
            return error("文件大小不能超过" + (maxFileSize / 1024 / 1024) + "MB");
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();

        // 检查文件类型
        String fileExtension = getFileExtension(fileName);
        if (StringUtils.isEmpty(fileExtension) || !isAllowedExtension(fileExtension)) {
            return error("不支持的文件类型，仅支持：" + allowedTypes);
        }

        String baseUploadPath = getBaseUploadPath();
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        String targetDirectory = baseUploadPath + datePath;

        File directory = new File(targetDirectory);
        if (!directory.exists()) {
            boolean mkdirResult = directory.mkdirs();
            if (!mkdirResult) {
                logger.error("无法创建目录: {}", targetDirectory);
                return error("服务器无法创建目录，请联系管理员");
            }
        }

        String encryptedFileName = generateEncryptedFileName(fileName);
        String fileFullPath = targetDirectory + File.separator + encryptedFileName + "." + fileExtension;

        // 保存文件
        File targetFile = new File(fileFullPath);
        try {
            file.transferTo(targetFile);
            logger.info("文件上传成功：{}", fileFullPath);

            // 构建文件信息
            Map<String, Object> fileInfo = new HashMap<>();
            fileInfo.put("fileName", fileName);
            fileInfo.put("fileSize", file.getSize());
            fileInfo.put("filePath", datePath + "/" + encryptedFileName + "." + fileExtension);
            String accessUrl = "/uploads/" + datePath.replace('\\', '/') + "/" + encryptedFileName + "." + fileExtension;
            fileInfo.put("url", accessUrl);
            return success("上传成功", fileInfo);
        } catch (IOException e) {
            logger.error("文件上传失败：", e);
            return error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 删除文件接口
     */
    @DeleteMapping("/delete")
    public AjaxResult deleteFile(@RequestParam("filePath") String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return error("文件路径不能为空");
        }

        // 防止路径遍历攻击
        if (filePath.contains("..") || filePath.contains("../")) {
            return error("无效的文件路径");
        }

        String baseUploadPath = getBaseUploadPath();
        String fullPath = baseUploadPath + filePath.replace("/uploads/", "");

        // 删除文件
        boolean result = FileUtils.deleteFile(fullPath);
        if (result) {
            return success("文件删除成功");
        } else {
            return error("文件删除失败，文件可能不存在");
        }
    }

    /**
     * 获取基础上传路径
     */
    private String getBaseUploadPath() {
        File uploadDir = new File(uploadPath);
        if (!uploadDir.isAbsolute()) {
            String userDir = System.getProperty("user.dir");
            return userDir + File.separator + uploadPath;
        }
        return uploadPath;
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }

        int lastDotIndex = fileName.lastIndexOf(".");
        if (lastDotIndex < 0) {
            return null;
        }

        return fileName.substring(lastDotIndex + 1).toLowerCase();
    }

    /**
     * 检查文件扩展名是否允许
     */
    private boolean isAllowedExtension(String extension) {
        String[] allowed = allowedTypes.split(",");
        for (String type : allowed) {
            if (type.trim().equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 生成加密的文件名
     */
    private String generateEncryptedFileName(String originalFileName) {
        String uniqueStr = originalFileName + System.currentTimeMillis() + Math.random();
        return Md5Utils.hash(uniqueStr);
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message, Object data) {
        return AjaxResult.success(message, data);
    }
}